package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.bean.LabelValueBean;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.domain.AlipayInfo;
import cc.rengu.redp.bizimpl.upmp.domain.BProdInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.service.IBProdInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IBProdInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpOrganizationService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.ProdInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.awt.SystemColor.info;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-10
 */

@Slf4j
@Api(tags = "产品管理:标准产品管理")
@RestController
@RequestMapping("/admin/mcmp/bProdInfo")
public class BProdInfoController extends BaseController {
    @Autowired
    private IBProdInfoService bProdInfoService;
    @Autowired
    private IUpmpOrganizationService organizationService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @GetMapping(value = "/list")
    public Map<String, Object> list(QueryRequest request, BProdInfo entity) {
        return getDataTable(this.bProdInfoService.findByPage(request, entity));
    }

    @Log("查询单条")
    @GetMapping(value = "/getOne")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "prodCode", value = "产品编码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", dataType = "String")
    })
    public BProdInfo getOne(@NotBlank(message = "{required}") String
                                    prodCode, String
                                    id, @NotBlank(message = "{required}") String instId) {
        if (StringUtils.isNotBlank(id)) {
            return bProdInfoService.getById(id);
        }
        LambdaQueryWrapper<BProdInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BProdInfo::getInstId, instId);
        wrapper.eq(BProdInfo::getProdCode, prodCode);
        return bProdInfoService.getOne(wrapper);
    }
    @GetMapping(value = "/subListEdit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "prodCode", value = "产品编码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", dataType = "String")
    })
    public Map<String, Object> getSubListEdit(@ModelAttribute("bProdInfo") BProdInfo entity) throws RedpException {
        return bProdInfoService.getSubList(entity);
    }

    @ApiOperation(value = "基础产品查询")
    @GetMapping(value = "/sublist")
    public Map<String, Object> getSubList(QueryRequest request, BProdInfo entity) throws RedpException {
            String optFlag = entity.getOptFlag();
            if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {//新增数据源
                return getDataTable(bProdInfoService.findAddProdInfoSubByPage(request, entity));
            } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag) || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)
                    || PageOptFlagEnum.OPT_FLAG_VIEW.getType().equals(optFlag)) {
                return getDataTable(bProdInfoService.findChckProdInfoSubByPage(request, entity));
            } else {
                return getDataTable(bProdInfoService.findUpdProdInfoSubByPage(request, entity));
            }
    }


    @ApiOperation(value = "页面切换查询")
    @GetMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "prodCode", value = "产品编码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "主操作类型：新增、修改、删除、审核等", required = true,dataType = "String")
    })
    public Map<String, Object> getEdit(BProdInfo entity) throws RedpException {
            return bProdInfoService.getEdit(entity);
    }

    //标准产品-基本产品页面信息保存(基本产品 配置页面保存)
    @ApiOperation("标准产品-基本产品 配置页面保存")
    @PutMapping("/edit")
    public OperationResult editSave(@Valid BProdInfo bProdInfo, HttpServletRequest request) throws RedpException {
        try {
            String optFlag = request.getParameter("optFlag");
            java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();

            //list 里提交的数据的几种情况  1：已经在界面点击选择并配置，已经入库；2：只是勾选，并未点击选择并配置，需要入库
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            UpmpOrganization org = organizationService.getOrgByUser(user, bProdInfo.getInstId());
            if (Common.isBlank(org)) {
                log.error("根据用户信息获取的机构号为空！");
                throw new RedpException("根据用户信息获取的机构号为空!");
            }
            BProdInfo entity = bProdInfoService.findProdByUK(bProdInfo.getInstId(), bProdInfo.getProdCode(), bProdInfo.getBaseProdCode());
            if (Common.isNotBlank(entity)) {
                //目前界面只能修改微信、支付宝通道类型
                entity.setWechatChannelId(bProdInfo.getWechatChannelId());
                entity.setAlipayChannelId(bProdInfo.getAlipayChannelId());
                entity.setOptFlag(bProdInfo.getOptFlag());
                entity.setOpt(bProdInfo.getOpt());
                entity.setProdName(bProdInfo.getProdName());
                entity.setProdDesc(bProdInfo.getProdDesc());
                entity.setBProdFeeList(bProdInfo.getBProdFeeList());
                entity.setBProdAuthCtrlList(bProdInfo.getBProdAuthCtrlList());
                entity.setBProdStageList(bProdInfo.getBProdStageList());
            } else {
                entity = bProdInfo;
            }
            return bProdInfoService.saveProdAndFollowersData(entity, user, org, optFlag);
        } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }



    @ApiOperation(value = "保存")
    @PostMapping("/subListEdit")
//    @RequiresPermissions("areaInfo:update")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "主操作类型:新增|修改|删除|审核等", required = true, dataType = "String")
    })
    public void subListEdit(ProdInfoVO prodInfoVO) throws RedpException {
        try {
            this.bProdInfoService.saveFromSubListPageData(prodInfoVO.getProdInfoList(),prodInfoVO.getOptFlag());
        } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    //标准产品管理列表页停用 启用
    @RequiresPermissions("产品管理:标准产品管理")
    @PostMapping(value = "/changeStatus")

    public void changeStatus(@ModelAttribute("bProdInfo") BProdInfo bProdInfo) {
        bProdInfoService.changeStatus(bProdInfo);
    }

    @Log("标准产品产品名称唯一性验证")
    @GetMapping(value = "/prodNameCheck")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "prodName", value = "产品名称", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "prodCode", value = "产品编号", dataType = "String")
    })
    public RedpResponse prodNameCheck(@NotBlank(message = "{required}") String
                                              prodName, String prodCode, @NotBlank(message = "{required}") String instId) throws RedpException {
        LambdaQueryWrapper<BProdInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BProdInfo::getInstId, instId);
        wrapper.eq(BProdInfo::getProdName, prodName);

        if (StringUtils.checkValNotNull(prodCode)) {
            wrapper.ne(BProdInfo::getProdCode, prodCode);
        }
        List<BProdInfo> list = bProdInfoService.list(wrapper);
        if (null != list && list.size() > 0) {
            throw new RedpException("[ 产品名称 ] 重复，请重新输入");
        }
        return new RedpResponse().message("验证成功");
    }
}
